package main

import (
	"http"
	"log"
	"cloud9lib.googlecode.com/hg/rest"
	"cloud9lib.googlecode.com/hg/index"
	"cloud9lib.googlecode.com/hg/sync"
)

var mux = http.NewServeMux()
var backoff = int64(1e8) //.1 secs
var bal = newBalancer()

type balancer struct {
	front chan string
	back chan string
}

func (b *balancer) pushFront(u string) {
	b.front <- u
}

func (b *balancer) pushBack(u string) {
	b.back <- u
}

func (b *balancer) pop() string {

	var res string

	// check front first	
	select {
	case res = <-b.front:
	default:
		// check back second
		select {
		case res = <-b.front:
		case res = <-b.back:
		}
	}

	return res
}

func newBalancer() *balancer {
	return &balancer{make(chan string, 100), make(chan string, 100)}
}

func (b *balancer) ServeHTTP(w http.ResponseWriter, req *http.Request) {

	u := b.pop()
	b.pushBack(u)

	http.Redirect(w, req, u + req.URL.RawPath, 302)
}

func onUpdate(url string) {

	log.Println("balanced: added new mux redirect: ", url)

	bal.pushFront(url)
}

func main () {

	rest.LogPrefix = "balanced: "

	err := index.AddRoute("root.cloud9lib.net/", "http://localhost:8080")

	if err != nil {
		panic(err)
	}

	http.Handle("/", rest.Log(bal))

	feed := sync.Feed(index.INDEX_URL, "muxes")

	go feed.Subscribe(0, nil, onUpdate)

	http.ListenAndServe(":8080", nil)
}
